import React, { useState, useEffect, useMemo } from "react"
import { DndContext, useSensors, useSensor, MouseSensor } from "@dnd-kit/core";
import { arrayMove, SortableContext, useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Spin, Button, Space, ImgDefault, Icon, message, Form, Input, Tag, ImgCrop, imgPreview, Modal, Checkbox, ImgUpload } from '@bytedance/mona-ui';
import { upImageItemFunc, getObjectURL, urlToBase64, shuffleArray } from '@contents/jinritemaiCopyGoods/copyDataFomate'

const MoveImageBpx = (props: any) => {
    const {
        imageData,
        removState,
        allList,
        onChange,
        index,
        aiImageList,
        getAiImageLodinStatus,
        aiNewObject
    } = props
    if (!imageData) return null

    const { setNodeRef, listeners, transform, transition } = useSortable({ id: imageData.id })

    const styles: any = {
        transform: CSS.Transform.toString(transform),
        transition: transition,
        zIndex: removState && removState === imageData.id ? 10 : 1,
        position: removState && removState === imageData.id ? 'relative' : 'static',
        opacity: removState && removState === imageData.id ? 0.5 : 1,
    }
    const [getAiImageStatus, setAiImageStatus] = useState(false)
    const [selectAiImage, setSelectAiImage] = useState<any>(null)


    return (
        <div className="moverbox" style={styles} ref={setNodeRef} {...listeners}>
            <Space direction="vertical" align="center">
                <Spin spinning={imageData.islodin}>
                    <div className="seterimage" style={{
                        cursor: 'move'
                    }}>
                        <img src={imageData.url} className="couyimage" />
                        <div className="conterItemStatus">
                            <div className="itemcie">
                                <Icon type="SeeIcon" className="setIcon" onClick={() => {
                                    imgPreview({
                                        defaultIndex: index,
                                        imgUrl: allList.map((res => res.url)),
                                    })
                                }}></Icon>
                            </div>
                            <div className="itemcie">
                                <Icon type="ClipIcon" className="setIcon" onClick={() => {
                                    ImgCrop.imgCropModalFun({
                                        image: imageData?.url,
                                        modalProps: {
                                            onOk: (e, newfile) => {
                                                console.log(e, newfile)
                                                const imageUrl = getObjectURL(newfile)
                                                allList[index].url = imageUrl
                                                allList[index].islodin = true
                                                allList[index].isNewImage = true
                                                allList[index].upStatus = false
                                                onChange && onChange([...allList])
                                                urlToBase64(imageUrl).then(resUrl => {
                                                    upImageItemFunc(resUrl).then((upImages) => {
                                                        allList[index].url = upImages.data[0]
                                                        allList[index].islodin = false
                                                        allList[index].isNewImage = true
                                                        allList[index].upStatus = true
                                                        onChange && onChange([...allList])
                                                    })
                                                })
                                            },
                                        },
                                    });
                                }}></Icon>
                            </div>
                            <div className="itemcie">
                                {/* <svg class="upload_hoverHeaderIcon__T2obv" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0_5_53182)"><circle cx="12.4712" cy="13.1951" r="9.6295" transform="rotate(-165 12.4712 13.1951)" fill="url(#paint0_linear_5_53182)"></circle><circle cx="13.8459" cy="11.8193" r="9.6295" transform="rotate(120 13.8459 11.8193)" fill="url(#paint1_linear_5_53182)"></circle><circle cx="11.095" cy="11.8195" r="9.6295" transform="rotate(-120 11.095 11.8195)" fill="url(#paint2_linear_5_53182)"></circle><path d="M21.7716 12.9361C20.3951 18.0731 15.1149 21.1217 9.97792 19.7452C4.84091 18.3688 1.79237 13.0885 3.16883 7.95153C4.54529 2.81452 9.82551 -0.234013 14.9625 1.14245C20.0995 2.5189 23.1481 7.79912 21.7716 12.9361Z" fill="url(#paint3_linear_5_53182)"></path><path opacity="0.8" fill-rule="evenodd" clip-rule="evenodd" d="M18.553 5.72691C18.8752 6.1224 19.1702 6.54875 19.4335 7.00478C21.4888 10.5647 21.0127 14.8915 18.5637 17.9008C16.2471 19.7908 13.0861 20.5782 9.97754 19.7453C8.61869 19.3812 7.40598 18.7439 6.38265 17.9084C3.92814 14.8988 3.44946 10.5676 5.50656 7.00461C5.768 6.55178 6.06067 6.12822 6.38027 5.73507C8.6966 3.84734 11.8558 3.06127 14.9626 3.89374C16.3195 4.25731 17.5306 4.89322 18.553 5.72691Z" fill="#1966FF"></path><path d="M10.8622 10.1067L12.2786 13.3754H10.7502C10.336 13.3754 10.0002 13.7112 10.0002 14.1254C10.0002 14.5396 10.336 14.8754 10.7502 14.8754H12.9286L13.437 16.0485C13.6017 16.4286 14.0433 16.6032 14.4234 16.4385C14.8035 16.2738 14.978 15.8322 14.8134 15.4521L11.7884 8.47153C11.443 7.67444 10.3154 7.66657 9.95895 8.45878L6.81624 15.4426C6.64627 15.8203 6.81468 16.2643 7.19241 16.4343C7.57014 16.6043 8.01415 16.4358 8.18413 16.0581L10.8622 10.1067Z" fill="url(#paint4_linear_5_53182)"></path><path d="M10.8622 10.1067L12.2786 13.3754H10.7502C10.336 13.3754 10.0002 13.7112 10.0002 14.1254C10.0002 14.5396 10.336 14.8754 10.7502 14.8754H12.9286L13.437 16.0485C13.6017 16.4286 14.0433 16.6032 14.4234 16.4385C14.8035 16.2738 14.978 15.8322 14.8134 15.4521L11.7884 8.47153C11.443 7.67444 10.3154 7.66657 9.95895 8.45878L6.81624 15.4426C6.64627 15.8203 6.81468 16.2643 7.19241 16.4343C7.57014 16.6043 8.01415 16.4358 8.18413 16.0581L10.8622 10.1067Z" fill="white"></path><path d="M17.0002 8.62537C17.0002 8.21115 16.6644 7.87537 16.2502 7.87537C15.836 7.87537 15.5002 8.21115 15.5002 8.62537V15.7504C15.5002 16.1646 15.836 16.5004 16.2502 16.5004C16.6644 16.5004 17.0002 16.1646 17.0002 15.7504V8.62537Z" fill="url(#paint5_linear_5_53182)"></path><path d="M17.0002 8.62537C17.0002 8.21115 16.6644 7.87537 16.2502 7.87537C15.836 7.87537 15.5002 8.21115 15.5002 8.62537V15.7504C15.5002 16.1646 15.836 16.5004 16.2502 16.5004C16.6644 16.5004 17.0002 16.1646 17.0002 15.7504V8.62537Z" fill="white"></path></g><defs><linearGradient id="paint0_linear_5_53182" x1="2.84168" y1="11.8194" x2="22.1007" y2="11.8194" gradientUnits="userSpaceOnUse"><stop stop-color="#1966FF" stop-opacity="0"></stop><stop offset="1" stop-color="#1966FF"></stop></linearGradient><linearGradient id="paint1_linear_5_53182" x1="4.21635" y1="10.4437" x2="23.4754" y2="10.4437" gradientUnits="userSpaceOnUse"><stop stop-color="#04CBE7" stop-opacity="0"></stop><stop offset="1" stop-color="#04CBE7"></stop></linearGradient><linearGradient id="paint2_linear_5_53182" x1="1.46545" y1="10.4438" x2="20.7245" y2="10.4438" gradientUnits="userSpaceOnUse"><stop stop-color="#3DAFFE" stop-opacity="0"></stop><stop offset="1" stop-color="#3DAFFE"></stop></linearGradient><linearGradient id="paint3_linear_5_53182" x1="3.52488" y1="6.62276" x2="22.1276" y2="11.6074" gradientUnits="userSpaceOnUse"><stop stop-color="#5859FE" stop-opacity="0"></stop><stop offset="1" stop-color="#5859FE"></stop></linearGradient><linearGradient id="paint4_linear_5_53182" x1="22.6815" y1="16.5004" x2="4.68146" y2="7.87536" gradientUnits="userSpaceOnUse"><stop stop-color="#D766FF"></stop><stop offset="0.460514" stop-color="#E0F2FF"></stop><stop offset="0.959811" stop-color="#66D8FF"></stop></linearGradient><linearGradient id="paint5_linear_5_53182" x1="22.6815" y1="16.5004" x2="4.68146" y2="7.87536" gradientUnits="userSpaceOnUse"><stop stop-color="#D766FF"></stop><stop offset="0.460514" stop-color="#E0F2FF"></stop><stop offset="0.959811" stop-color="#66D8FF"></stop></linearGradient><clipPath id="clip0_5_53182"><rect width="24" height="24" fill="white"></rect></clipPath></defs></svg> */}
                                <Icon type="DeleteIcon" className="setIcon" onClick={() => {
                                    allList.splice(index, 1)
                                    allList.forEach((res, index) => {
                                        res.id = index + 1
                                    })
                                    onChange && onChange([...allList])
                                }}></Icon>
                            </div>
                        </div>
                    </div>
                </Spin>
                <Button onClick={() => setAiImageStatus(true)} size="mini" type="secondary" >更换AI图片</Button>
            </Space>

            <Modal
                title="AI智能生成"
                visible={getAiImageStatus}
                onOk={() => {
                    if (!selectAiImage) return message.error('请选择图片')
                    allList[index].url = selectAiImage
                    onChange && onChange([...allList])
                    setAiImageStatus(false)

                }}
                onCancel={() => setAiImageStatus(false)}
                width={740}
            >
                <Spin spinning={getAiImageLodinStatus} tip="正在AI生成图片， 请稍后">
                    <div className="bu" style={{
                        minHeight: 200
                    }}>
                        <Button type="link" onClick={() => {
                            if (aiNewObject && aiNewObject.run) {
                                aiNewObject.run(imageData.url)
                            }
                        }} style={{
                            marginBottom: 10,
                            // width: '100%',
                        }}>继续生成</Button>
                        <Space wrap size={15} style={{
                            marginBottom: 0,
                            width: '100%',
                        }}>
                            {aiImageList.map((item, index) => {
                                return <div className="tuerConters" onClick={() => {
                                    setSelectAiImage(item)
                                }}>
                                    <ImgDefault imgSrc={item} style={{ width: 120, height: 120, margin: "0 auto 10px" }} key={index}></ImgDefault>
                                    {selectAiImage == item && <div className="selectTiter">
                                        <Checkbox checked={true} />
                                    </div>}
                                </div>
                            })}
                            <Spin spinning={aiNewObject?.run_status == 4} style={{
                                width: 120,
                            }}></Spin>
                        </Space>
                    </div>

                </Spin>
            </Modal>
        </div>
    )
}
const RomoItemBox = (props: any) => {
    const { data, onChange, aiImageList, getAiImageLodinStatus, aiNewObject } = props
    if (!data) return null
    const [list, setList] = useState<any[]>(data)
    useEffect(() => {
        if (data !== list) {
            onChange && onChange(list)
        }
    }, [list])
    useMemo(() => {
        setList(data)
    }, [data])
    const [removState, setRemoveState] = useState(false)
    const sensors = useSensors(
        useSensor(MouseSensor, {
            activationConstraint: {
                distance: 5, // 按住不动移动5px 时 才进行拖拽, 这样就可以触发点击事件
            },
        })
    )
    return <DndContext
        sensors={sensors}
        onDragStart={(e: any) => {
            const { active } = e
            setRemoveState(active.id)
        }}
        onDragEnd={(e) => {
            setRemoveState(false)
            const { active, over } = e
            if (!over || !over.id) return
            let activeIndex
            let overIndex
            list.forEach((val, index) => {
                if (val.id === active.id) {
                    activeIndex = index
                }
                if (val.id === over.id) {
                    overIndex = index
                }
            })
            setList(items => {
                const adddata = arrayMove(items, activeIndex, overIndex)
                return adddata
            })
        }}>

        <SortableContext items={[...list]}>
            <div className="topmovuerfoter-tower" style={{
                display: 'flex',
            }}>

                {list.map((res: any, index: number) => {
                    return (<MoveImageBpx
                        key={res.id}
                        imageData={res}
                        removState={removState}
                        allList={list}
                        onChange={setList}
                        index={index}
                        aiImageList={aiImageList}
                        getAiImageLodinStatus={getAiImageLodinStatus}
                        aiNewObject={aiNewObject}
                    />)
                })}
                {list.length < 5 && <ImgUpload
                    accept="image/*"
                    wrapWidth={102}
                    wrapHeight={102}
                    isRequest={false}
                    maxCount={1}
                    fileList={[]}
                    beforeUpload={async (file: any) => {
                        console.log('file', file)
                        const fileType = /\image\/\/*/
                        if (fileType.test(file.type)) {
                            const imageUrl = getObjectURL(file)
                            let upTiemImaghId = list.length + 1
                            // 判断图片比例是否为1:1
                            const img = new Image()
                            img.src = imageUrl
                            img.onload = () => {
                                const { width, height } = img
                                if (width !== height) {
                                    message.error('请上传1:1比例的图片')
                                    return
                                }
                                urlToBase64(imageUrl).then(resUrl => {
                                    upImageItemFunc(resUrl).then((upImages) => {
                                        console.log('upImages', upImages, list)
                                        // list.push({
                                        //     id: upTiemImaghId,
                                        //     url: upImages.data[0],
                                        //     isNewImage: false,
                                        //     islodin: false,
                                        //     upStatus: true

                                        // })
                                        // setList([...list])
                                        const itemtser = list.find((item) => item.id == upTiemImaghId)
                                        itemtser.url = upImages.data[0]
                                        itemtser.islodin = false
                                        itemtser.upStatus = true
                                        setList([...list])
                                        // setPicDataImage({ ...picDataImage })
                                        // setPicImageList([...picImageList])
                                    })
                                })

                                // 走一个上传
                                list.push({
                                    id: upTiemImaghId,
                                    url: imageUrl,
                                    isNewImage: true,
                                    islodin: true,
                                    upStatus: false

                                })
                                setList([...list])

                            }



                            // picDataImage.list.push({
                            //     id: upTiemImaghId,
                            //     url: imageUrl,
                            //     islodin: true,
                            //     isNewImage: true,
                            //     upStatus: false
                            // })
                            // setPicDataImage({ ...picDataImage })
                            // setPicImageList([...picImageList])
                            return
                        }
                        message.error("仅支持图片")
                    }}
                />}
            </div>

        </SortableContext>
    </DndContext>
}
function ZhutuList(props: any) {
    const { data, onChange, aiImageList, getAiImageLodinStatus, aiNewObject } = props
    if (!data) return null
    return <><RomoItemBox data={data} aiImageList={aiImageList} getAiImageLodinStatus={getAiImageLodinStatus} aiNewObject={aiNewObject} onChange={(e) => {
        onChange && onChange(e)
    }} /></>
}

export default ZhutuList